# If debugging, set the `DEBUG' variable to `make' to something non-empty.

LIBNAME = rxpoly
LIBSONAME = lib$(LIBNAME).so.0
LIBFNAME = $(LIBSONAME).1.2
LIBPATH = lib/$(LIBFNAME)

DISTNAME = librxpoly-v0.1.2.tgz

ifdef DEBUG
DBGPRM = -g -gdwarf-2 -g3
else
DBGPRM = -O4 -march=native
endif

.PHONY: all
all : $(LIBPATH)

$(LIBPATH) : src/rxpoly.c
	mkdir -p lib
	gcc -fpic -shared -Wl,-soname,$(LIBSONAME) -o $@ $< -lc $(DBGPRM)
	ln -s $(LIBFNAME) lib/$(LIBSONAME) >/dev/null 2>&1 || true
	ln -s $(LIBSONAME) lib/lib$(LIBNAME).so >/dev/null 2>&1 || true


FUNCTIONS = matches firstMatch nextMatch nextDisjunctMatch allMatches substitute
TESTS_C = $(foreach f,$(FUNCTIONS),test/$(f)Test.c)
TESTS_EXE = $(foreach f,$(FUNCTIONS),test/$(f)Test)
TESTS = $(foreach f,$(FUNCTIONS),test_$(f))
DISTFILES = COPYING Makefile doc/dokumentace.pdf src/rxpoly.c src/rxpoly.h $(TESTS_C)

.PHONY: test $(TESTS)
test: test_matches test_firstMatch
test: test_nextMatch
test: test_nextDisjunctMatch
test: test_allMatches
test: test_substitute

$(TESTS) : test_% : test/%Test
	LD_LIBRARY_PATH="$$LD_LIBRARY_PATH:lib" $<

$(TESTS_EXE) : test/% : test/%.c $(LIBPATH)
	@echo -n "Compiling \`$*'..."
	@gcc -L "`readlink -e lib`" -l $(LIBNAME) $< $(DBGPRM) -o $@
	@echo -e '\tReady.'


$(LIBPATH) $(TESTS_EXE) : .debugChanged

ifdef DEBUG
.debugChanged : .dodebug
.dodebug : .dontdebug
else
.debugChanged : .dontdebug
.dontdebug : .dodebug
endif
.debugChanged :
	touch $@

.dodebug .dontdebug :
	touch $< -t 197001020001
	touch $@

.PHONY: trtest
trtest src/trtest: src/trtest.c
	gcc src/trtest.c -o src/trtest
	src/trtest

.PHONY: ctest
ctest src/ctest: src/ctest.c
	gcc src/ctest.c -o src/ctest
	src/ctest


doc/dokumentace.pdf : doc/dokumentace.tex
	pdflatex $<

.PHONY: dist
dist $(DISTNAME) : $(DISTFILES)
	tar tzvf $(DISTNAME) $^
